package com.promis.crypto.digest;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class MacKeyDigest {

	private final static String KEY_ALGORITHM = "HmacMD5";
	
	private static MacKeyDigest keyCipher;
	
	public synchronized static MacKeyDigest getInstance() {
		if (keyCipher == null) {
			keyCipher = new MacKeyDigest();
		}
		return keyCipher;
	}
	
	public SecretKey createSecretKey() throws NoSuchAlgorithmException {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
		return keyGenerator.generateKey();
	}
	
	public SecretKey toSecretKey(byte[] secretKey) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
	    return new SecretKeySpec(secretKey, KEY_ALGORITHM);
	}
	
	public byte[] toSecretKey(SecretKey secretKey) {
		return secretKey.getEncoded();
	}
	
	public byte[] digest(byte[] data, SecretKey secretKey) throws Exception {  
		Mac mac = Mac.getInstance(KEY_ALGORITHM);  
		mac.init(secretKey);
		return mac.doFinal(data);
	}
}
